package en.edu.zucc.pb.loginapplication.db;
//package en.edu.zucc.pb.loginapplication.util;

import androidx.sqlite.db.SimpleSQLiteQuery;

//import com.example.moments.dao.BaseDao;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.List;

//import en.edu.zucc.pb.loginapplication.AppDatabase;

//extends SQLiteOpenHelper
public class RoomUtil {
//    public SQLiteDatabase getDatabase() {
//        return getDatabase(false);
//    }
//
//    public SQLiteDatabase getDatabase(boolean forceWritable) {
//        try {
//            return forceWritable ? getWritableDatabase() : getReadableDatabase();
//        } catch (IllegalStateException e) {
//            return this.db;
//        }
//    }

    public static String q(Object object) {
        return " '" + object + "' ";
    }

    enum ColumnType{
        UNDERSCORE,CAMEL,PASCAL,NO_CHANGE
//        underscore,camel
    }

    /**
     * 根据实体名字
     *
     * @param object
     * @param sql
     * @return
     * @throws IllegalAccessException
     */
    public static StringBuilder where(Object object, StringBuilder sql) throws
            IllegalAccessException {
//        TblOrder tblOrder = new TblOrder();
//        tblOrder.setCarId(1);

        Field[] declaredFields = object.getClass().getDeclaredFields();

//        ColumnType columnType=ColumnType.PASCAL;
        ColumnType columnType= ColumnType.NO_CHANGE;
        int index = 1;
        boolean first = true;
        for (Field field : declaredFields) {
            field.setAccessible(true);

//            System.out.println("获取到字段：" + field.getType().getCanonicalName()
//                    + ",值：" + field.get(object));
            int modifiers = field.getModifiers();
            if (Modifier.isStatic(modifiers)) {
//                if (!getStatic) {
//                    continue;
//                }
                continue;
            }
//            field.i
//判断 field 是什么类型
//            int

            Object val = field.get(object);
            if (val == null) {
                continue;
            }
//            ""的字符串 也不搜索嘛
            if (val instanceof String) {
                if (val.equals("")) {
                    continue;
                }
            }


//            String canonicalName = field.getType().getCanonicalName();
//            String packaging = BeanUtil.primaryToPackaging(canonicalName);

            String name = field.getName();
//            orderId== name
//            String underscoreName = StringUtils.underscoreName(name);
//            String underscoreName = StringUtils.underscoreNameLower(name);
            String columnName=name;
            if(columnType== ColumnType.UNDERSCORE){
                columnName= underscoreNameLower(name);
            }else if(columnType== ColumnType.NO_CHANGE){
                columnName=name;
            }

//            String underscoreName = underscoreNameLower(name);
//            underscoreName  order_id
            if (first) {
//                sql.append(" where ").append(underscoreName).append(" = ").append(q(val));
                sql.append(" where ").append(columnName).append(" = ").append(q(val));
//                sql += " where "+underscoreName+" = " + q(val);
                first = false;
            } else {
//                sql += " and "+underscoreName+" = " + q(val);
//                sql.append(" and ").append(underscoreName).append(" = ").append(q(val));
                sql.append(" and ").append(columnName).append(" = ").append(q(val));
//                sql += "and car_status = " + q(carStatus);
            }

//            if(canonicalName.)
//            set(pst, index, val, packaging);
            index++;

        }

//        Integer carStatus = obj.getCarStatus();
//        if (carStatus != null) {
//            if (first) {
//                sqlInsert += "where car_status = " + q(carStatus);
//                first = false;
//            } else {
//                sqlInsert += "and car_status = " + q(carStatus);
//            }
//
//        }
        return sql;
    }

    /**
     * 数据库 是可以大写的
     * https://blog.csdn.net/xianrenmodel/article/details/110792291
     * 将驼峰式命名的字符串转换为下划线大写方式。如果转换前的驼峰式命名的字符串为空，则返回空字符串。
     * 例如：HelloWorld->HELLO_WORLD
     *
     * @param name 转换前的驼峰式命名的字符串
     * @return 转换后下划线大写方式命名的字符串
     */
    public static String underscoreName(String name) {
        StringBuilder result = new StringBuilder();
        if (name != null && name.length() > 0) {
            // 将第一个字符处理成大写
            result.append(name.substring(0, 1).toUpperCase());
            // 循环处理其余字符
            for (int i = 1; i < name.length(); i++) {
                String s = name.substring(i, i + 1);
                // 在大写字母前添加下划线
                if (s.equals(s.toUpperCase()) && !Character.isDigit(s.charAt(0))) {
                    result.append("_");
                }
                // 其他字符直接转成大写
                result.append(s.toUpperCase());
            }
        }
        return result.toString();
    }

    /**
     * 数据库 是可以大写的
     * https://blog.csdn.net/xianrenmodel/article/details/110792291
     * 将驼峰式命名的字符串转换为下划线小写方式。如果转换前的驼峰式命名的字符串为空，则返回空字符串。
     * 例如：HelloWorld->hello_world
     *
     * @param name 转换前的驼峰式命名的字符串
     * @return 转换后下划线大写方式命名的字符串
     */
    public static String underscoreNameLower(String name) {
        String underscoreName = underscoreName(name);
        return underscoreName.toLowerCase();

    }


    public static StringBuilder whereLike(Object object, StringBuilder sql) throws
            IllegalAccessException {
//        TblOrder tblOrder = new TblOrder();
//        tblOrder.setCarId(1);
        Field[] declaredFields = object.getClass().getDeclaredFields();


        int index = 1;
        boolean first = true;
        for (Field field : declaredFields) {
            field.setAccessible(true);

//            System.out.println("获取到字段：" + field.getType().getCanonicalName()
//                    + ",值：" + field.get(object));
            int modifiers = field.getModifiers();
            if (Modifier.isStatic(modifiers)) {
//                if (!getStatic) {
//                    continue;
//                }
                continue;
            }
//            field.i
//判断 field 是什么类型
//            int

            Object val = field.get(object);
            if (val == null) {
                continue;
            }
//            ""的字符串 也不搜索嘛
            if (val instanceof String) {
                if (val.equals("")) {
                    continue;
                }
            }


//            String canonicalName = field.getType().getCanonicalName();
//            String packaging = BeanUtil.primaryToPackaging(canonicalName);

            String name = field.getName();
//            orderId== name
//            String underscoreName = StringUtils.underscoreName(name);
            String underscoreName = underscoreNameLower(name);
//            String underscoreName = StringUtils.underscoreNameLower(name);
//            underscoreName  order_id
            if (first) {
                sql.append(" where ").append(underscoreName).append(" like ").append(l(val));
//                sql += " where "+underscoreName+" = " + q(val);
                first = false;
            } else {
//                sql += " and "+underscoreName+" = " + q(val);
                sql.append(" and ").append(underscoreName).append(" like ").append(l(val));
//                sql += "and car_status = " + q(carStatus);
            }

//            if(canonicalName.)
//            set(pst, index, val, packaging);
            index++;

        }

//        Integer carStatus = obj.getCarStatus();
//        if (carStatus != null) {
//            if (first) {
//                sqlInsert += "where car_status = " + q(carStatus);
//                first = false;
//            } else {
//                sqlInsert += "and car_status = " + q(carStatus);
//            }
//
//        }
        return sql;
    }

    static String l(Object o) {
        return " '%" + o + "%' ";
//        new FlowLayout(FlowLayout.CENTER)
    }


//    public static <T> List<T> select(T obj) {
////        Connection conn = DBUtil.getConnection();
//        String sql = "select * from  " + getTableName(obj) + "   ";
//        List<T> by = select(conn, sql, obj);
////        DBUtil.closeConnection(conn);
//        return by;
//    }

//    public static <T> List<T> getBy(T obj) throws DbException, SQLException {
//        Connection conn = DBUtil.getConnection();
//        String sql = "select * from  " + getTableName(obj) + "   ";
//        List<T> by = getBy(conn, sql, obj);
//        DBUtil.closeConnection(conn);
//        return by;
//    }

//    public static <T> List<T> select(T obj, T likeObj){
//        Connection conn = DBUtil.getConnection();
//        String sql = "select * from  " + getTableName(obj) + "   ";
//        List<T> by = select(conn, sql, obj, likeObj, null);
////        dd
//        DBUtil.closeConnection(conn);
//        return by;
//    }


    public static <T> List<T> select(BaseDao<T> dao, T obj) throws IllegalAccessException {
        String sql = "select * from  " + getTableName(obj) + "   ";
        List<T> select = select(dao, sql, obj);
        return select;
    }


    //    https://www.cnblogs.com/Marydon20170307/p/14149970.html
//    public static <T> List<T> select(Connection conn, T obj, String tableName) throws DbException {
//        String sql = "select * from  " + tableName + "   ";
//        List<T> by = select(conn, sql, obj);
//        return by;
//    }

    public static <T> List<T> select(BaseDao<T> dao, String sql, T obj) throws  IllegalAccessException {

//        如果 addsql 是null 那就不会去添加 addsql
        return select(dao, sql, obj, null,null);
    }

    public static <T> String getTableName(T obj) {
        String tableName = obj.getClass().getSimpleName();
//        tableName = underscoreNameLower(tableName);
//        这里貌似不用 下划线了 而且是 Entity
//        tableName = StringUtils.underscoreNameLower(tableName);
        return tableName;
    }


    public static <T> String getSelectSqlStr(String sql, T obj,
                                             T likeObj, String addSql) throws IllegalAccessException {
        StringBuilder stringBuilder = new StringBuilder(sql);
        StringBuilder sqlNow = where(obj, stringBuilder);
        if (likeObj != null) {
            whereLike(likeObj, stringBuilder);
        }

//            sel  * where id= 1 and ..
//            and time <= ? and time >= ?
        if (addSql != null) {
            sqlNow.append("   ").append(addSql);
//            int where = sqlNow.indexOf("where");
//            sqlNow.replace(where,where+5,"and");

            int whereStart = sqlNow.indexOf(" where ");
            if (whereStart == -1) {

                int andStart = sqlNow.indexOf(" and ");
                if (andStart != -1) {
                    sqlNow.replace(andStart, andStart + 5, " where ");
                }
//                如果没有 and ，就不用替换了  ， 也就是 没有and 也没有where

            }
            //            有where  就不管

        }

        return String.valueOf(sqlNow);
//            sqlNow+=addSql;
//            String sqlStr = String.valueOf(sqlNow);
//            sqlStr += addSql;
//         PreparedStatement pst = conn.prepareStatement(String.valueOf(sqlNow));
    }


    public static <T> List<T> select(BaseDao<T> dao, String sql, T obj,
                                     T likeObj, String addSql) throws IllegalAccessException {

        String selectSqlStr = getSelectSqlStr(sql, obj, likeObj, addSql);
        SimpleSQLiteQuery query = new SimpleSQLiteQuery(selectSqlStr);
        List<T> viaQuery2 = dao.getViaQuery(query);
        return viaQuery2;
//
//        try {
////            https://blog.csdn.net/weixin_26744853/article/details/108167419
////         new SimpleSQLiteQuery()
//            StringBuilder stringBuilder = new StringBuilder(sql);
//            StringBuilder sqlNow = where(obj, stringBuilder);
//            if (likeObj != null) {
//                whereLike(likeObj, stringBuilder);
//            }
//
////            sel  * where id= 1 and ..
////            and time <= ? and time >= ?
//            if (addSql != null) {
//                sqlNow.append("   ").append(addSql);
////            int where = sqlNow.indexOf("where");
////            sqlNow.replace(where,where+5,"and");
//
//                int whereStart = sqlNow.indexOf(" where ");
//                if (whereStart == -1) {
//
//                    int andStart = sqlNow.indexOf(" and ");
//                    if (andStart != -1) {
//                        sqlNow.replace(andStart, andStart + 5, " where ");
//                    }
////                如果没有 and ，就不用替换了  ， 也就是 没有and 也没有where
//
//                }
//                //            有where  就不管
//
//            }
//
//
////            sqlNow+=addSql;
////            String sqlStr = String.valueOf(sqlNow);
////            sqlStr += addSql;
//            PreparedStatement pst = conn.prepareStatement(String.valueOf(sqlNow));
//
//
////            https://blog.csdn.net/m0_37168878/article/details/83375849
//            SimpleSQLiteQuery query = new SimpleSQLiteQuery(String.valueOf(sqlNow));
//            BaseDao<Comment> baseDao = null;
//            List<Comment> viaQuery1 = baseDao.getViaQuery(query);
//            AppDatabase database;
////            https://blog.csdn.net/m0_37168878/article/details/83375849
//            List viaQuery = database.getBaseDao().getViaQuery(query);
////            搜索出来应该是直接是 合理的 对象吧
////            database.getUserDao().
//            User user2 = rawDao.getUserViaQuery(query);
//            ResultSet resultSet = pst.executeQuery();
//
//            List<T> list = new ArrayList<>();
//            while (resultSet.next()) {
//
//                T type = getInstanceNoParam(obj);
//
//                putValToObj(resultSet, type);
//
//                list.add(type);
//
//            }
//
//            try (Cursor cursor = getDatabase().rawQuery(query, null)) {
//
//                if (cursor.moveToFirst()) {
//                    do {
//                        int i = 0;
//                        Note note = new Note();
//                        note.setCreation(cursor.getLong(i++));
//                        note.setLastModification(cursor.getLong(i++));
//                        note.setTitle(cursor.getString(i++));
//                        note.setContent(cursor.getString(i++));
//                        note.setArchived("1".equals(cursor.getString(i++)));
//                        note.setTrashed("1".equals(cursor.getString(i++)));
//                        note.setAlarm(cursor.getString(i++));
//                        note.setReminderFired(cursor.getInt(i++));
//                        note.setRecurrenceRule(cursor.getString(i++));
//                        note.setLatitude(cursor.getString(i++));
//                        note.setLongitude(cursor.getString(i++));
//                        note.setAddress(cursor.getString(i++));
//                        note.setLocked("1".equals(cursor.getString(i++)));
//                        note.setChecklist("1".equals(cursor.getString(i++)));
//
//                        // Eventual decryption of content
////          内容的最终解密
//                        if (Boolean.TRUE.equals(note.isLocked())) {
//                            note.setContent(
//                                    Security.decrypt(note.getContent(), Prefs.getString(PREF_PASSWORD, "")));
//                        }
//
//                        // Set category
//                        long categoryId = cursor.getLong(i++);
//                        if (categoryId != 0) {
//                            Category category = new Category(categoryId, cursor.getString(i++),
//                                    cursor.getString(i++), cursor.getString(i));
//                            note.setCategory(category);
//                        }
//
//                        // Add eventual attachments uri
////          添加最终附件uri
//                        note.setAttachmentsList(getNoteAttachments(note));
//
//                        // Adding note to list
////          向列表中添加 笔记
//                        noteList.add(note);
//
//                    } while (cursor.moveToNext());
//                }
//
//            }
//
//            return list;
//
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            throw new DbException(ex);
//        }
    }

//    public static <T> List<T> select(Connection conn, String sql, T obj,
//                                     T likeObj, String addSql) throws DbException {
//
//        try {
////            https://blog.csdn.net/weixin_26744853/article/details/108167419
////         new SimpleSQLiteQuery()
//            StringBuilder stringBuilder = new StringBuilder(sql);
//            StringBuilder sqlNow = where(obj, stringBuilder);
//            if (likeObj != null) {
//                whereLike(likeObj, stringBuilder);
//            }
//
////            sel  * where id= 1 and ..
////            and time <= ? and time >= ?
//            if (addSql != null) {
//                sqlNow.append("   ").append(addSql);
////            int where = sqlNow.indexOf("where");
////            sqlNow.replace(where,where+5,"and");
//
//                int whereStart = sqlNow.indexOf(" where ");
//                if (whereStart == -1) {
//
//                    int andStart = sqlNow.indexOf(" and ");
//                    if (andStart != -1) {
//                        sqlNow.replace(andStart, andStart + 5, " where ");
//                    }
////                如果没有 and ，就不用替换了  ， 也就是 没有and 也没有where
//
//                }
//                //            有where  就不管
//
//            }
//
//
////            sqlNow+=addSql;
////            String sqlStr = String.valueOf(sqlNow);
////            sqlStr += addSql;
//            PreparedStatement pst = conn.prepareStatement(String.valueOf(sqlNow));
//
//
////            https://blog.csdn.net/m0_37168878/article/details/83375849
//            SimpleSQLiteQuery query = new SimpleSQLiteQuery(String.valueOf(sqlNow));
//            BaseDao<Comment> baseDao = null;
//            List<Comment> viaQuery1 = baseDao.getViaQuery(query);
//            AppDatabase database;
////            https://blog.csdn.net/m0_37168878/article/details/83375849
//            List viaQuery = database.getBaseDao().getViaQuery(query);
////            搜索出来应该是直接是 合理的 对象吧
////            database.getUserDao().
//            User user2 = rawDao.getUserViaQuery(query);
//            ResultSet resultSet = pst.executeQuery();
//
//            List<T> list = new ArrayList<>();
//            while (resultSet.next()) {
//
//                T type = getInstanceNoParam(obj);
//
//                putValToObj(resultSet, type);
//
//                list.add(type);
//
//            }
//
//            try (Cursor cursor = getDatabase().rawQuery(query, null)) {
//
//                if (cursor.moveToFirst()) {
//                    do {
//                        int i = 0;
//                        Note note = new Note();
//                        note.setCreation(cursor.getLong(i++));
//                        note.setLastModification(cursor.getLong(i++));
//                        note.setTitle(cursor.getString(i++));
//                        note.setContent(cursor.getString(i++));
//                        note.setArchived("1".equals(cursor.getString(i++)));
//                        note.setTrashed("1".equals(cursor.getString(i++)));
//                        note.setAlarm(cursor.getString(i++));
//                        note.setReminderFired(cursor.getInt(i++));
//                        note.setRecurrenceRule(cursor.getString(i++));
//                        note.setLatitude(cursor.getString(i++));
//                        note.setLongitude(cursor.getString(i++));
//                        note.setAddress(cursor.getString(i++));
//                        note.setLocked("1".equals(cursor.getString(i++)));
//                        note.setChecklist("1".equals(cursor.getString(i++)));
//
//                        // Eventual decryption of content
////          内容的最终解密
//                        if (Boolean.TRUE.equals(note.isLocked())) {
//                            note.setContent(
//                                    Security.decrypt(note.getContent(), Prefs.getString(PREF_PASSWORD, "")));
//                        }
//
//                        // Set category
//                        long categoryId = cursor.getLong(i++);
//                        if (categoryId != 0) {
//                            Category category = new Category(categoryId, cursor.getString(i++),
//                                    cursor.getString(i++), cursor.getString(i));
//                            note.setCategory(category);
//                        }
//
//                        // Add eventual attachments uri
////          添加最终附件uri
//                        note.setAttachmentsList(getNoteAttachments(note));
//
//                        // Adding note to list
////          向列表中添加 笔记
//                        noteList.add(note);
//
//                    } while (cursor.moveToNext());
//                }
//
//            }
//
//            return list;
//
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            throw new DbException(ex);
//        }
//    }


//    @Override
//    public void onCreate(SQLiteDatabase db) {
//
//    }
//
//    @Override
//    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//
//    }

//    只有select 可以 rawqu
//    public static <T> void delete(BaseDao<T> dao, T obj) throws
//            IllegalAccessException {
//        delete(conn, obj, getTableName(obj));
////        USER_PHONE
//    }
//
//
//    public static <T> void delete(T obj) throws DbException,
//            IllegalAccessException, SQLException {
//        Connection conn = DBUtil.getConnection();
//        delete(conn, obj, getTableName(obj));
//        DBUtil.closeConnection(conn);
////        USER_PHONE
//    }
//
//    public static <T> void delete(BaseDao<T> dao,T obj, String tableName) throws
//            IllegalAccessException{
//
//        String sqlDel = "DELETE  FROM  " + tableName + "  ";
//
//        StringBuilder stringBuilder = new StringBuilder(sqlDel);
////        表上的 null 会变成 0
//        StringBuilder where = where(obj, stringBuilder);
//
//        dao.clearAll();
//        PreparedStatement pst = conn.prepareStatement(String.valueOf(where));
//        pst.execute();
//        pst.close();
////			pstByPlanName.setInt(1, stepId);
////
////        try {
////
////            PreparedStatement pst = conn.prepareStatement(sql);
////
//////            填 问号
////            JdbcUtil.set(pst, obj);
////            pst.execute();
////            pst.close();
////
////        } catch (Exception ex) {
////            ex.printStackTrace();
////            throw new DbException(ex);
////        }
//    }
//
//
//    public static <T> void delete(Connection conn, String sql, T obj) throws DbException {
//
//        try {
//
//            PreparedStatement pst = conn.prepareStatement(sql);
//
////            填 问号
//            JdbcUtil.set(pst, obj);
//            pst.execute();
//            pst.close();
//
//        } catch (Exception ex) {
//            ex.printStackTrace();
//            throw new DbException(ex);
//        }
//    }

}
